/*
 * Author - Lukasz Baranski <barluk87@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 */


#include "uart.h"

#define BAUD 9600

#include <avr/io.h>
#include <avr/interrupt.h>

#include <util/setbaud.h>



volatile unsigned char fifoPtrHome, fifoPtrEnd, uartFifo[FIFO_LEN];

void initUart(void){

		UCSRB=(1<<RXEN)|(1<<TXEN);
		UCSRC=(1<<URSEL)|(3<<UCSZ0);
		UBRRH=UBRRH_VALUE; 
		UBRRL=UBRRL_VALUE;
		fifoPtrHome=0x0; 
		fifoPtrEnd=0x0;
		}


char sendByte(unsigned char byte){
    /*
    *   fifoPtrEnd++
    *   ISR uart enable
    *
    */
    uartFifo[fifoPtrEnd]=byte;

    fifoPtrEnd++;
    if(fifoPtrEnd == FIFO_LEN){
        fifoPtrEnd=0;
    }
	//if(fifoPtrEnd == fifoPtrHome){

	//}

    UCSRB|=(1<<UDRIE);
	return 0;
}

char sendArray(char* ptr, unsigned char len){
    /*
    *   fifoPtrEnd+=len
    *   ISR uart enable
    *
    */
    unsigned char i;

    for(i=0; i<len; i++){
        uartFifo[fifoPtrEnd++]=ptr[i];
        if(fifoPtrEnd == FIFO_LEN)
            fifoPtrEnd=0;
    }
    UCSRB|=(1<<UDRIE);
    return 0;
}

ISR(USART_UDRE_vect){
    
    UDR=uartFifo[fifoPtrHome];
    fifoPtrHome++;
    if(fifoPtrHome == FIFO_LEN){
        fifoPtrHome = 0;
    }
    if(fifoPtrHome == fifoPtrEnd){
		UCSRB&=~(1<<UDRIE);
    }
}
